/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "plugins/ecmascript/runtime/ecma_string-inl.h"
#include "plugins/ecmascript/runtime/ecma_global_storage-inl.h"
#include "plugins/ecmascript/runtime/ecma_vm.h"
#include "plugins/ecmascript/runtime/js_handle.h"
#include "plugins/ecmascript/runtime/object_factory.h"
#include "plugins/ecmascript/tests/runtime/common/test_helper.h"

// NOLINTNEXTLINE(google-build-using-namespace)
using namespace ark::ecmascript;

// NOLINTBEGIN(readability-magic-numbers,readability-redundant-string-cstr,modernize-avoid-c-arrays)

namespace ark::test {
class JSHandleTest : public testing::Test {
public:
    static void SetUpTestCase()
    {
        GTEST_LOG_(INFO) << "SetUpTestCase";
    }

    static void TearDownTestCase()
    {
        GTEST_LOG_(INFO) << "TearDownCase";
    }

    void SetUp() override
    {
        TestHelper::CreateEcmaVMWithScope(instance_, thread_, scope_);
    }

    void TearDown() override
    {
        TestHelper::DestroyEcmaVMWithScope(instance_, scope_);
    }

protected:
    // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes)
    JSThread *thread_ {nullptr};

private:
    PandaVM *instance_ {nullptr};
    ecmascript::EcmaHandleScope *scope_ {nullptr};
};

TEST_F(JSHandleTest, NewGlobalHandle)
{
    ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
    auto global = thread_->GetEcmaGlobalStorage();

    uintptr_t globalString = 0;
    {
        [[maybe_unused]] EcmaHandleScope scopeNested(thread_);
        auto string1 = factory->NewFromString("test1");
        globalString = global->NewGlobalHandle(string1.GetTaggedType());
    }
    // trigger GC
    thread_->GetEcmaVM()->CollectGarbage();

    // check result
    EXPECT_TRUE(factory->NewFromString("test1")->Compare(*reinterpret_cast<EcmaString **>(globalString)) == 0);
}

static void FillGlobalString(uintptr_t globalString[], int length, EcmaGlobalStorage *global, ObjectFactory *factory,
                             JSThread *thread)
{
    {
        [[maybe_unused]] EcmaHandleScope scopeNested(thread);
        for (int i = 0; i < length; i++) {
            std::string test = "test" + std::to_string(i);
            auto string1 = factory->NewFromString(test.c_str());
            // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
            globalString[i] = global->NewGlobalHandle(string1.GetTaggedType());
        }
    }
}

TEST_F(JSHandleTest, NewGlobalHandle1)
{
    ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
    auto global = thread_->GetEcmaGlobalStorage();

    uintptr_t globalString[600] = {0};
    FillGlobalString(globalString, 600, global, factory, thread_);
    // trigger GC
    thread_->GetEcmaVM()->CollectGarbage();
    for (int i = 300; i > 200; i--) {
        global->DisposeGlobalHandle(globalString[i]);
    }
    // check result
    for (int i = 0; i <= 200; i++) {
        std::string test = "test" + std::to_string(i);
        EXPECT_TRUE(factory->NewFromString(test.c_str())->Compare(*reinterpret_cast<EcmaString **>(globalString[i])) ==
                    0);
    }
    // trigger GC
    thread_->GetEcmaVM()->CollectGarbage();
    for (int i = 301; i < 600; i++) {
        std::string test = "test" + std::to_string(i);
        EXPECT_TRUE(factory->NewFromString(test.c_str())->Compare(*reinterpret_cast<EcmaString **>(globalString[i])) ==
                    0);
    }
}

TEST_F(JSHandleTest, DisposeGlobalHandle)
{
    ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
    auto global = thread_->GetEcmaGlobalStorage();

    uintptr_t globalString[600] = {0};
    FillGlobalString(globalString, 600, global, factory, thread_);
    for (int i = 512; i > 200; i--) {
        global->DisposeGlobalHandle(globalString[i]);
    }
    int count = 0;
    global->IterateUsageGlobal([&count](EcmaGlobalStorage::Node *node) {
        JSTaggedValue value(node->GetObject());
        EXPECT_TRUE(value.IsString());
        count++;
    });
    EXPECT_TRUE(count == 288);
}

TEST_F(JSHandleTest, DisposeAndNewGlobalHandle)
{
    ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
    auto global = thread_->GetEcmaGlobalStorage();

    uintptr_t globalString[768] = {0};
    FillGlobalString(globalString, 768, global, factory, thread_);
    for (int i = 767; i > 200; i--) {
        global->DisposeGlobalHandle(globalString[i]);
    }
    // trigger GC
    thread_->GetEcmaVM()->CollectGarbage();
    {
        [[maybe_unused]] EcmaHandleScope scopeNested(thread_);
        for (int i = 200; i < 400; i++) {
            std::string test = "test" + std::to_string(i);
            auto string1 = factory->NewFromString(test.c_str());
            globalString[i] = global->NewGlobalHandle(string1.GetTaggedType());
        }
    }
    // check result
    for (int i = 0; i <= 300; i++) {
        std::string test = "test" + std::to_string(i);
        EXPECT_TRUE(factory->NewFromString(test.c_str())->Compare(*reinterpret_cast<EcmaString **>(globalString[i])) ==
                    0);
    }
}

TEST_F(JSHandleTest, DISABLED_NewWeakGlobalHandle)
{
    ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
    auto global = thread_->GetEcmaGlobalStorage();

    uintptr_t globalString = 0;
    {
        [[maybe_unused]] EcmaHandleScope scopeNested(thread_);
        auto string1 = factory->NewFromString("test1");
        globalString = global->NewGlobalHandle(string1.GetTaggedType());
        globalString = global->SetWeak(globalString);

        // trigger GC
        thread_->GetEcmaVM()->CollectGarbage();

        // check result
        EXPECT_TRUE(factory->NewFromString("test1")->Compare(*reinterpret_cast<EcmaString **>(globalString)) == 0);
        EXPECT_TRUE(global->IsWeak(globalString));
    }
    // trigger GC
    thread_->GetEcmaVM()->CollectGarbage();

    // check weak reference
    JSTaggedType result = *reinterpret_cast<JSTaggedType *>(globalString);
    EXPECT_TRUE(result == JSTaggedValue::Undefined().GetRawData());
}

TEST_F(JSHandleTest, DISABLED_NewWeakGlobalHandle1)
{
    ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
    auto global = thread_->GetEcmaGlobalStorage();

    uintptr_t globalString[800] = {0};
    {
        [[maybe_unused]] EcmaHandleScope scopeNested(thread_);
        for (int i = 0; i < 800; i++) {
            std::string test = "test" + std::to_string(i);
            auto string1 = factory->NewFromString(test.c_str());
            globalString[i] = global->NewGlobalHandle(string1.GetTaggedType());
            globalString[i] = global->SetWeak(globalString[i]);
            EXPECT_TRUE(global->IsWeak(globalString[i]));
        }
        for (int i = 600; i > 200; i--) {
            global->DisposeGlobalHandle(globalString[i]);
        }
        // trigger GC
        thread_->GetEcmaVM()->CollectGarbage();
        // check result
        for (int i = 0; i <= 200; i++) {
            std::string test = "test" + std::to_string(i);
            EXPECT_TRUE(
                factory->NewFromString(test.c_str())->Compare(*reinterpret_cast<EcmaString **>(globalString[i])) == 0);
        }
    }
    // trigger GC
    thread_->GetEcmaVM()->CollectGarbage();
    for (int i = 601; i < 800; i++) {
        EXPECT_TRUE(*reinterpret_cast<TaggedType *>(globalString[i]) == JSTaggedValue::Undefined().GetRawData());
    }
}
}  // namespace ark::test

// NOLINTEND(readability-magic-numbers,readability-redundant-string-cstr,modernize-avoid-c-arrays)
